package com.mimo.logic.message.config;

import java.time.Duration;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.annotation.Validated;

import com.mimo.common.logic.dto.msg.DispatchMsgType;

/**
 * 用于限制上行消息的速率，包括 P2P， P2R消息
 * 
 * @author Hongyu
 */
@Configuration(proxyBeanMethods = false)
@ConfigurationProperties(prefix = "logic.message.constraints")
@Validated
public class MessageUpstreamConstraintsConfig {

  // 配置项这里，只支持 P2P和Peer2Room
  private static Set<DispatchMsgType> allowTypes = EnumSet.of(DispatchMsgType.P2P, DispatchMsgType.Peer2Room);

  @Valid
  @NotEmpty
  @Size(min = 2, max = 2)
  private Map<DispatchMsgType, UpstreamConstraintsItem> upstreams;

  public Map<DispatchMsgType, UpstreamConstraintsItem> getUpstreams() {
    return upstreams;
  }

  public void setUpstreams(Map<DispatchMsgType, UpstreamConstraintsItem> upstreams) {
    this.upstreams = upstreams;
  }

  @PostConstruct
  private void init() {
    if (upstreams.keySet().stream().anyMatch(t -> !allowTypes.contains(t))) {
      throw new IllegalArgumentException("配置upstream type 只支持 P2P和Peer2Room");
    }
  }

  // ---------------------------------------------------------------------------------------------------
  @Validated
  public static class UpstreamConstraintsItem {

    @NotNull
    private Duration duration;

    @NotNull
    private Integer count;// 数量

    public Duration getDuration() {
      return duration;
    }

    public void setDuration(Duration duration) {
      this.duration = duration;
    }

    public Integer getCount() {
      return count;
    }

    public void setCount(Integer count) {
      this.count = count;
    }

  }

}
